<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>websocket测试</title>
    <script type="text/javascript" src="jquery-2.1.3.min.js"></script>
    <script type="text/javascript">
        var webSocket = new WebSocket('ws://localhost:8002');
        webSocket.onerror = function (event) {
            onError(event)
        };

        webSocket.onopen = function (event) {
            onOpen(event)
        };

        webSocket.onmessage = function (event) {
            onMessage(event)
        };

        function onMessage(event) {
            document.getElementById('messages').innerHTML += '<br />' + event.data;
        }

        function onOpen(event) {
            document.getElementById('messages').innerHTML = '连接已建立';
        }

        function onError(event) {
            alert(event.data);
        }

        function start() {
            var text = document.getElementById("userinput").value;

            webSocket.send(text);
            return false;
        }
    </script>
</head>
<body>

<div>
    <input type="text" id="userinput"/> <br> <input type="submit" value="发送" onclick="start()"/>
</div>
<div id="messages"></div>
</body>
</html>